package com.acceptable.qucun.generic.filter;

import com.acceptable.qucun.generic.util.CodeUtil;
import com.acceptable.qucun.generic.util.result.ResultUtil;
import com.acceptable.qucun.generic.util.result.error.GenericErrorResult;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebFilter(filterName = "secretFilter", urlPatterns = "/*")
public class SecretFilter implements Filter {

    /**
     * 将传来的Base64的加密数据进行解密
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
         // axios 默认以 Content-Type: application/json 格式发送
         /*
            该格式数据存在request.inputStream 属性中
            可通过jackson ObjectMapper 进行解析 (取出流中数据并删除)
         */

         // Content-Type: multipart/form-data
         /*
            request.getParameterMap request.getParameterNames request.getParts 三者互不影响
            但均影响
                new ServletFileUpload(new DiskFileItemFactory()).parseRequest(HttpServletRequest)
                三者均导致解析后获取的List为空
            前两个均不含前端文件数据 唯独 request.getParts能获取文件的二进制数据
            ServletFileUpload.parseRequest 获取数据后 影响Controller通过@RequestParam/@RequestPart 取出数据
        */

//        System.out.println("com.acceptable.web.qucun.other.filter.SecretFilter.doFilter");

        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        if("get".equals(request.getMethod().toLowerCase())){
            filterChain.doFilter(request, response);
            return;
        }

        Map<String, String> dataMap = null;
        String contentType = request.getContentType();

        try{
            if(contentType.contains("multipart/form-data")){
                dataMap = CodeUtil.formDataBase64Decode(request);
            } else if(contentType.contains("application/x-www-form-urlencoded")){
                dataMap = CodeUtil.urlencodedBase64Decode(request.getInputStream());
            } else if(contentType.contains("application/json")){
                dataMap = CodeUtil.jsonBase64Decode(request.getInputStream());
            }
        } catch (IllegalArgumentException e){
            response.getWriter().write(ResultUtil.error(GenericErrorResult.DATA_CODE_ERROR));
            return;
        }

        request.setAttribute("data_map", dataMap);
        filterChain.doFilter(request, response);
    }
}
